package com.zjpavt.client.util;

import com.zjpavt.client.command.kcommand.KCommandManager;
import com.zjpavt.client.job.JobManager;
import com.zjpavt.client.job.JobRunner;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * linux下指令执行类
 *
 * @author cjp
 */
public class CmdUtil {

    private static final Logger log = LoggerFactory.getLogger(CmdUtil.class);


    /**
     * @param command 仅用于执行不关注或是没有返回结果的命令  如kill
     */
    public static void execCmd(String command) throws IOException, InterruptedException {
        BufferedReader br = null;
        try {
            Process p = Runtime.getRuntime().exec(command);
            br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            p.waitFor();
        }
        finally {
            if (br != null) {
                br.close();
            }
        }
    }

    public static void reboot() throws IOException, InterruptedException {
        execCmd("reboot");
    }

    public static void restartClient() throws IOException, InterruptedException {
        String startClientShell = ClientConfig.PAVT_PATH + "bin/startClient.sh";
        File startClientShellFile = new File(startClientShell);
        if (!startClientShellFile.exists()) {
            FileUtil.writeToFile(startClientShellFile.getAbsolutePath(), "java -jar /pavt/bin/PavtUpdate.jar -ko &\n" +
                                 "java -jar /pavt/bin/client.jar &");
        }
        execCmd("sh " + startClientShellFile.getAbsolutePath());
    }

    /**
     * 重新dhcp
     */
    public static void udhcpc() {
        try {
            CmdUtil.execCmd("udhcpc");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置新的时间
     * @param date
     * @throws IOException
     * @throws InterruptedException
     */
    public static synchronized void setDate(Date date) throws IOException, InterruptedException {
        //和当前时间差距小于1秒时不再修改
        if (Math.abs(date.getTime() - System.currentTimeMillis()) < 1000) {
            Date oldDate = new Date();
            SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy.MM.dd-HH:mm:ss");
            String dateStr = sdfDate.format(date);
            String commandSetDate = "date -s " + dateStr;
            CmdUtil.execCmd(commandSetDate);
            log.info("old date is "+oldDate.toString()+ "new date is" + new Date().toString());
//			系统时钟同步到硬件时钟 否则会和文件一样一段时间内的修改不生效
            commandSetDate = "hwclock -w";
            CmdUtil.execCmd(commandSetDate);
            log.debug("time too close so wont set");
            return;
//		如果误差时间小于一分钟 不重排指令
        } else if(Math.abs(date.getTime() - System.currentTimeMillis()) < 1000 *60) {
            Date oldDate = new Date();
            SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy.MM.dd-HH:mm:ss");
            String dateStr = sdfDate.format(date);
            String commandSetDate = "date -s " + dateStr;
            CmdUtil.execCmd(commandSetDate);
            log.info("old date is "+oldDate.toString()+ "new date is" + new Date().toString());
//			系统时钟同步到硬件时钟 否则会和文件一样一段时间内的修改不生效
            commandSetDate = "hwclock -w";
            CmdUtil.execCmd(commandSetDate);
            return;
        }
        Date oldDate = new Date();
        final JobManager jobManager = JobManager.getInstance();
        //before setDate
        //如果当时正在处于K指令或者光控指令需要去取消，防止时间被调整以后指令执行时间过长或者任务失效
        jobManager.cancelTempJob();
        //清除掉文件中的k指令的时长，
        KCommandManager kManager = KCommandManager.getInstance();
        kManager.clearKCommand();
        kManager.clearKCommandWithTime();
        //需要在设置时间之前取消所有的离线指令，并取消所有的timer，否则可能出现timer失效以及计划任务一次全部执行
        jobManager.cancelOfflineCommandJob();
        jobManager.cancelTodayTimerJob();
        //setDate
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy.MM.dd-HH:mm:ss");
        String dateStr = sdfDate.format(date);
        String commandSetDate = "date -s " + dateStr;
        CmdUtil.execCmd(commandSetDate);
        log.info("old date is "+oldDate.toString()+ "new date is" + new Date().toString());
        commandSetDate = "hwclock -w";
        CmdUtil.execCmd(commandSetDate);
        //After setDate
        final JobRunner jobRunner = JobRunner.getInstance();
        jobRunner.sendOfflineCommandOfToday();
        jobRunner.sendTodayTimerCommand();
        jobRunner.refreshTodayTimerCommand();
        try {
            jobManager.initDailyDayJob();
        } catch (SchedulerException e) {
            log.error(LoggerUtil.convertException2String(e));
        }
        //LoggerUtil.reloadLogger(); TODO 重启无效 暂时关闭
    }


}
